﻿Imports GuildCMS.Account.Management
Imports System.Data.SqlClient
Imports System.Web.Configuration

Namespace Account
    Public Class _Default
        Inherits System.Web.UI.Page

#Region " Database variables "

        ''' <summary>
        ''' Set the database connection variables used throughout this class.
        ''' </summary>
        ''' <remarks>Placed here so they will not need to be typed out each time they are needed.</remarks>
        Private connectionString As String = WebConfigurationManager.ConnectionStrings("SqlConnectionString").ConnectionString()
        Private connection As SqlConnection = New SqlConnection(connectionString)
        Private command As New SqlCommand

#End Region

#Region " Page events. "

        ''' <summary>
        ''' Handles the Load event of the Page control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            ' This is a protected page so check that the member is logged into the system using CheckLogin(True).
            CheckLogin(True)

            ' Check to see if the user has a main character selected and if not display a message.
            If Session("MainCharacter") = 0 Then
                lblSelectMainNow.Visible = True
            Else
                lblSelectMainNow.Visible = False
            End If


            ' Create a dataset containing the information on the logged in members characters.
            CreateCharacterDataSet()
        End Sub

#End Region

        ''' <summary>
        ''' Registers the values for the cascading drop downs. (Fixes form validation issues with AJAX.)
        ''' </summary>
        Protected Sub RegisterValuesForCombos()
            ddlGame.DataBind()
            ddlRealm.DataBind()
            ddlFaction.DataBind()
            ddlRace.DataBind()
            ddlClass.DataBind()
            'ddlGender.DataBind()
        End Sub

#Region " DataSet creation "

        ''' <summary>
        ''' Creates the DataSet and relationships used in the nested repeaters to display a members current charaters broke down by game and realm.
        ''' </summary>
        Private Sub CreateCharacterDataSet()
            command = New SqlCommand("sp_public_GetCharacters", connection)
            command.CommandType = CommandType.StoredProcedure
            command.Parameters.Add("@Member_Id", SqlDbType.NVarChar, 50)
            command.Parameters("@Member_Id").Value = Session("MemberId")
            Dim da As New SqlDataAdapter(command)
            Dim ds As New DataSet()
            da.Fill(ds)

            ds.Relations.Add(New DataRelation("Game2Realm", ds.Tables(0).Columns("Game_Id"), ds.Tables(1).Columns("Realm_Game")))
            ds.Relations.Add(New DataRelation("Realm2Character", ds.Tables(1).Columns("Realm_Id"), ds.Tables(2).Columns("Character_Realm")))

            repGames.DataSource = ds.Tables(0)
            repGames.DataBind()
        End Sub

#End Region

#Region " Item DataBinding for the list of current characters. "

        ''' <summary>
        ''' Databind the repGames control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterItemEventArgs" /> instance containing the event data.</param>
        Protected Sub repGames_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
            If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
                Dim drv As DataRowView = TryCast(e.Item.DataItem, DataRowView)
                Dim repRealms As Repeater = TryCast(e.Item.FindControl("repRealms"), Repeater)
                repRealms.DataSource = drv.CreateChildView("Game2Realm")
                repRealms.DataBind()
            End If
        End Sub

        ''' <summary>
        ''' Databinds the repRealms control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterItemEventArgs" /> instance containing the event data.</param>
        Protected Sub repRealms_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
            If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
                Dim drv As DataRowView = TryCast(e.Item.DataItem, DataRowView)
                Dim repCharaters As Repeater = TryCast(e.Item.FindControl("repCharaters"), Repeater)
                repCharaters.DataSource = drv.CreateChildView("Realm2Character")
                repCharaters.DataBind()
            End If
        End Sub

#End Region

        ''' <summary>
        ''' Adds a new charater to the database on the click event of the btnAddCharater control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        Protected Sub btnAddCharater_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAddCharater.Click
            If Page.IsValid Then
                ' Add the new charater to the database.
                Try
                    command = New SqlCommand("sp_public_addCharacter", connection)
                    command.CommandType = CommandType.StoredProcedure
                    command.Parameters.Add("@MemberId", SqlDbType.Int)
                    command.Parameters("@MemberId").Value = Session("MemberId")
                    command.Parameters.Add("@Name", SqlDbType.NVarChar, 100)
                    command.Parameters("@Name").Value = txtName.Text
                    command.Parameters.Add("@Game", SqlDbType.Int)
                    command.Parameters("@Game").Value = ddlGame.SelectedValue
                    command.Parameters.Add("@Realm", SqlDbType.Int)
                    command.Parameters("@Realm").Value = ddlRealm.SelectedValue
                    command.Parameters.Add("@Faction", SqlDbType.Int)
                    command.Parameters("@Faction").Value = ddlFaction.SelectedValue
                    command.Parameters.Add("@Race", SqlDbType.Int)
                    command.Parameters("@Race").Value = ddlRace.SelectedValue
                    command.Parameters.Add("@Class", SqlDbType.Int)
                    command.Parameters("@Class").Value = ddlClass.SelectedValue
                    'command.Parameters.Add("@Gender", SqlDbType.Int)
                    'command.Parameters("@Gender").Value = ddlGender.SelectedValue
                    connection.Open()
                    command.ExecuteNonQuery()
                Catch ex As Exception

                Finally
                    connection.Close()
                End Try

                ' Redirect the user to the same page in order to show the new character in the list of characters.
                Response.Redirect("~/Account/")
            End If
        End Sub

#Region " Form OnServerValidate procedures. "

        ''' <summary>
        ''' Handles the ServerValidate event of the valName control.
        ''' </summary>
        ''' <param name="source">The source of the event.</param>
        ''' <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs" /> instance containing the event data.</param>
        Protected Sub valName_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Set args.IsValid to True by default.
            args.IsValid = True

            ' Check that the supplied character name has content.
            If txtName.Text = Nothing Then
                valName.ErrorMessage = "This field is required."
                args.IsValid = False
            End If

            ' Check that the length of the name supplied is no more then 100 charaters in length.
            If txtName.Text.Length() > 100 Then
                valName.ErrorMessage = "Please enter no more then 100 charaters."
                args.IsValid = False
            End If

            ' Check that this character does not already exist within the database.
            Try
                command = New SqlCommand("sp_public_countCharacters", connection)
                command.CommandType = CommandType.StoredProcedure
                command.Parameters.Add("@Name", SqlDbType.NVarChar, 100)
                command.Parameters("@Name").Value = txtName.Text
                command.Parameters.Add("@Game", SqlDbType.Int)
                command.Parameters("@Game").Value = ddlGame.SelectedValue
                command.Parameters.Add("@Realm", SqlDbType.Int)
                command.Parameters("@Realm").Value = ddlRealm.SelectedValue
                command.Parameters.Add("@Total", SqlDbType.Int)
                command.Parameters("@Total").Direction = ParameterDirection.Output
                connection.Open()
                command.ExecuteNonQuery()
                Dim totalRows As Integer = CInt(command.Parameters("@Total").Value)
                If totalRows > 0 Then
                    valName.ErrorMessage = "Character name already exists."
                    args.IsValid = False
                End If
            Catch ex As Exception
                ' Any exception will cause args.IsValid to equal False.
                valName.ErrorMessage = "There was an error processing this field."
                args.IsValid = False
            Finally
                connection.Close()
            End Try
        End Sub

        ''' <summary>
        ''' Handles the ServerValidate event of the valGame control.
        ''' </summary>
        ''' <param name="source">The source of the event.</param>
        ''' <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs" /> instance containing the event data.</param>
        Protected Sub valGame_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Set args.IsValid to True by default.
            args.IsValid = True

            ' Check that a game was selected.
            If ddlGame.SelectedValue = Nothing Then
                valGame.ErrorMessage = "This field is required."
                args.IsValid = False
            End If
        End Sub

        ''' <summary>
        ''' Handles the ServerValidate event of the valRealm control.
        ''' </summary>
        ''' <param name="source">The source of the event.</param>
        ''' <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs" /> instance containing the event data.</param>
        Protected Sub valRealm_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Set args.IsValid to True by default.
            args.IsValid = True

            ' Check that a realm was selected.
            If ddlRealm.SelectedValue = Nothing Then
                valRealm.ErrorMessage = "This field is required."
                args.IsValid = False
            End If
        End Sub

        ''' <summary>
        ''' Handles the ServerValidate event of the valFaction control.
        ''' </summary>
        ''' <param name="source">The source of the event.</param>
        ''' <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs" /> instance containing the event data.</param>
        Protected Sub valFaction_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Set args.IsValid to True by default.
            args.IsValid = True

            ' Check that a faction was selected.
            If ddlFaction.SelectedValue = Nothing Then
                valFaction.ErrorMessage = "This field is required."
                args.IsValid = False
            End If
        End Sub

        ''' <summary>
        ''' Handles the ServerValidate event of the valRace control.
        ''' </summary>
        ''' <param name="source">The source of the event.</param>
        ''' <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs" /> instance containing the event data.</param>
        Protected Sub valRace_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Set args.IsValid to True by default.
            args.IsValid = True

            ' Check that a race was selected.
            If ddlRace.SelectedValue = Nothing Then
                valRace.ErrorMessage = "This field is required."
                args.IsValid = False
            End If
        End Sub

        ''' <summary>
        ''' Handles the ServerValidate event of the valClass control.
        ''' </summary>
        ''' <param name="source">The source of the event.</param>
        ''' <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs" /> instance containing the event data.</param>
        Protected Sub valClass_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Set args.IsValid to True by default.
            args.IsValid = True

            ' Check that a class was selected.
            If ddlClass.SelectedValue = Nothing Then
                valClass.ErrorMessage = "This field is required."
                args.IsValid = False
            End If
        End Sub

        ' ''' <summary>
        ' ''' Handles the ServerValidate event of the valGender control.
        ' ''' </summary>
        ' ''' <param name="source">The source of the event.</param>
        ' ''' <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs" /> instance containing the event data.</param>
        Protected Sub valGender_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Set args.IsValid to True by default.
            args.IsValid = True

            ' Check that a class was selected.
            If ddlGender.SelectedValue = Nothing Then
                valGender.ErrorMessage = "This field is required."
                args.IsValid = False
            End If
        End Sub

#End Region

    End Class
End Namespace